package net.bingosoft.common.struts.action;

import java.io.File;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.bingosoft.common.util.FileHelper;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DownloadAction;
import org.springframework.util.Assert;

/**
 * 2007-9-4 下午03:35:49
 * Author:yangdongyu(yangdy@bingosoft.net)
 * ReadMe:通用的下载文件的action
 * ChangeLog:
 */
public class CommonDownloadAction extends DownloadAction {
	/**
	 * 待下载文件的路径
	 */
	private static final String filePath = "FILE_PATH";
	/**
	 * 待下载的文件路径是否是上下文相关的
	 */
	private static final String isRelativePath = "IS_RELATIVE_PATH";
	
	private static final Log log = LogFactory.getLog(CommonDownloadAction.class);

	/* (non-Javadoc)
	 * @see org.apache.struts.actions.DownloadAction#getStreamInfo(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
	 */
	@Override
	protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		log.debug("Enter into getStreamInfo ...");
		String filePathAndName = request.getParameter(filePath);		
		boolean isRelative = Boolean.valueOf(request.getParameter(isRelativePath));
		Assert.notNull(filePathAndName,"待下载文件名称不能为空");
		log.debug("待下载文件的路径为: " + filePathAndName);
		String mimeType = FileHelper.getFileMimeType(filePathAndName);
		log.debug("mimeType : " + mimeType);
		String fileName = FileHelper.getRealFileName(filePathAndName);
		response.setHeader("Content-disposition","attachment; filename=" + FileHelper.encodeFileName(fileName));
		return isRelative ? new ResourceStreamInfo(mimeType, servlet.getServletContext(),filePathAndName):new FileStreamInfo(mimeType,new File(filePathAndName));
	}

}
